package com.business.dashboard.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 * 
 * @author Claude
 * @since 2025-07-06
 */
@Component
public class JwtUtil {

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    /**
     * 生成用户JWT token
     */
    public String generateToken(String userId) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("type", "user");
        return createToken(claims, userId);
    }

    /**
     * 生成管理员JWT token
     */
    public String generateAdminToken(String adminId) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("adminId", adminId);
        claims.put("type", "admin");
        return createToken(claims, adminId);
    }

    /**
     * 创建token
     */
    private String createToken(Map<String, Object> claims, String subject) {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 从token中获取用户ID
     */
    public String getUserIdFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getSubject();
    }

    /**
     * 从token中获取管理员ID
     */
    public String getAdminIdFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return (String) claims.get("adminId");
    }

    /**
     * 从token中获取token类型
     */
    public String getTokenType(String token) {
        Claims claims = getClaimsFromToken(token);
        return (String) claims.get("type");
    }

    /**
     * 检查是否为管理员token
     */
    public Boolean isAdminToken(String token) {
        try {
            String type = getTokenType(token);
            return "admin".equals(type);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 检查是否为用户token
     */
    public Boolean isUserToken(String token) {
        try {
            String type = getTokenType(token);
            return "user".equals(type);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 从token中获取声明信息
     */
    private Claims getClaimsFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 检查token是否过期
     */
    public Boolean isTokenExpired(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            Date expiration = claims.getExpiration();
            return expiration.before(new Date());
        } catch (Exception e) {
            return true;
        }
    }

    /**
     * 验证token
     */
    public Boolean validateToken(String token, String userId) {
        try {
            String userIdFromToken = getUserIdFromToken(token);
            return userIdFromToken.equals(userId) && !isTokenExpired(token);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 刷新token
     */
    public String refreshToken(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            claims.setIssuedAt(new Date());
            return createToken(claims, claims.getSubject());
        } catch (Exception e) {
            return null;
        }
    }

}